<template>
  <div class="recharge-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-header">充值总收益</div>
        <div class="stat-amount">¥ {{ formatAmount(totalRevenue) }}</div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form ref="queryRef" :model="queryParams" inline class="search-form">
        <el-form-item label="订单编号">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单编号"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="充值渠道">
          <el-select v-model="queryParams.rechargeChannel" placeholder="请选择充值渠道" clearable class="search-select">
            <el-option label="全部" value="" />
            <el-option label="小程序" value="小程序" />
            <el-option label="APP" value="APP" />
            <el-option label="H5" value="H5" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易状态">
          <el-select v-model="queryParams.tradeStatus" placeholder="请选择交易状态" clearable class="search-select">
            <el-option label="全部" value="" />
            <el-option label="待支付" value="待支付" />
            <el-option label="支付成功" value="支付成功" />
            <el-option label="支付失败" value="支付失败" />
            <el-option label="已退款" value="已退款" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="search-btn">
            搜索
          </el-button>
          <el-button @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <div class="table-header">
        <div class="header-left">
          <span class="header-title">会员充值记录</span>
          <div class="header-tips">
            <el-tooltip content="待支付：等待用户支付" placement="top">
              <el-tag type="warning" size="small">待支付</el-tag>
            </el-tooltip>
            <el-tooltip content="支付成功：充值已完成" placement="top">
              <el-tag type="success" size="small">支付成功</el-tag>
            </el-tooltip>
            <el-tooltip content="支付失败：充值失败" placement="top">
              <el-tag type="danger" size="small">支付失败</el-tag>
            </el-tooltip>
            <el-tooltip content="已退款：订单已退款" placement="top">
              <el-tag type="info" size="small">已退款</el-tag>
            </el-tooltip>
          </div>
        </div>
        <div class="header-stats">
          <span class="stat-item">
            总记录: <span class="total-text">{{ total }}</span>
          </span>
        </div>
      </div>
      
      <el-table 
        v-loading="loading" 
        :data="recordList" 
        stripe
        border
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#fafafa', color: '#666', fontWeight: '500' }"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="用户名" align="center" prop="username" min-width="100">
          <template #default="scope">
            <div class="user-info">
              <el-icon class="user-icon"><User /></el-icon>
              {{ scope.row.username }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="mobile" width="120" />
        <el-table-column label="订单编号" align="center" prop="orderNo" min-width="140" show-overflow-tooltip />
        <el-table-column label="充值渠道" align="center" prop="rechargeChannel" width="100">
          <template #default="scope">
            <el-tag :type="getChannelType(scope.row.rechargeChannel)" size="small">
              {{ scope.row.rechargeChannel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="会员类别" align="center" prop="faceValueName" min-width="120">
          <template #default="scope">
            <div class="member-level">
              <el-icon class="level-icon"><Star /></el-icon>
              {{ scope.row.faceValueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="面额金额" align="center" prop="faceValue" width="100">
          <template #default="scope">
            <div class="amount-cell">
              <span class="amount-text">¥{{ formatAmount(scope.row.faceValue) }}</span>
              <small class="amount-label">面额</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="实付金额" align="center" prop="rechargeFee" width="100">
          <template #default="scope">
            <div class="amount-cell">
              <span class="amount-text success">¥{{ formatAmount(scope.row.rechargeFee) }}</span>
              <small class="amount-label">实付</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="促销" align="center" prop="isPromotion" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isPromotion == 1 ? 'success' : ''" size="small">
              {{ scope.row.isPromotion == 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="赠送余额" align="center" prop="balanceQuantity" width="100">
          <template #default="scope">
            <span v-if="scope.row.giveBalance == 1" class="gift-text">
              +¥{{ formatAmount(scope.row.balanceQuantity) }}
            </span>
            <span v-else class="text-muted">无</span>
          </template>
        </el-table-column>
        <el-table-column label="赠送优惠券" align="center" prop="couponDesc" min-width="120">
          <template #default="scope">
            <span v-if="scope.row.giveCoupon == 1" class="coupon-text">
              {{ scope.row.couponDesc }}
            </span>
            <span v-else class="text-muted">无</span>
          </template>
        </el-table-column>
        <el-table-column label="交易状态" align="center" prop="tradeStatus" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.tradeStatus)" size="small" effect="light">
              {{ scope.row.tradeStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <div class="time-cell">
              <el-icon class="time-icon"><Clock /></el-icon>
              <span>{{ formatTime(scope.row.createTime) }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>
</template>

<script setup name="Record">
import { ref, reactive, toRefs, getCurrentInstance, onMounted, nextTick } from 'vue'
import { listRecord } from "@/api/order/record"
import { User, Star, Clock, Download } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

const recordList = ref([])
const loading = ref(true)
const total = ref(0)
const totalRevenue = ref(249.40) // 充值总收益

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    mobile: null,
    rechargeChannel: null,
    tradeStatus: null
  }
})

const { queryParams } = toRefs(data)

/** 查询会员充值记录列表 */
function getList() {
  console.log('开始加载数据...')
  loading.value = true
  
  listRecord(queryParams.value).then(response => {
    console.log('API 响应:', response)
    recordList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
    
    // 计算总收益
    calculateTotalRevenue()
    console.log('数据加载完成，记录数:', recordList.value.length)
  }).catch(error => {
    console.error('查询失败:', error)
    loading.value = false
    
    // 如果API调用失败，使用模拟数据作为后备
    console.log('API调用失败，使用模拟数据')
    recordList.value = [
      {
        id: 1,
        username: '张三',
        mobile: '13800138000',
        orderNo: 'R202401010001',
        rechargeChannel: '小程序',
        faceValueName: '普通会员',
        faceValue: 100,
        rechargeFee: 99,
        discountPrice: 99,
        isPromotion: 1,
        giveBalance: 1,
        balanceQuantity: 10,
        giveCoupon: 1,
        couponDesc: '新用户专享券',
        tradeStatus: '支付成功',
        createTime: '2024-01-01T10:30:00',
        description: '首次充值'
      },
      {
        id: 2,
        username: '李四',
        mobile: '13900139000',
        orderNo: 'R202401010002',
        rechargeChannel: 'APP',
        faceValueName: '青铜会员',
        faceValue: 200,
        rechargeFee: 180,
        discountPrice: 180,
        isPromotion: 1,
        giveBalance: 1,
        balanceQuantity: 20,
        giveCoupon: 0,
        couponDesc: null,
        tradeStatus: '支付成功',
        createTime: '2024-01-01T14:20:00',
        description: '促销活动充值'
      },
      {
        id: 3,
        username: '王五',
        mobile: '13700137000',
        orderNo: 'R202401010003',
        rechargeChannel: 'H5',
        faceValueName: '黄金会员',
        faceValue: 500,
        rechargeFee: 450,
        discountPrice: 450,
        isPromotion: 0,
        giveBalance: 1,
        balanceQuantity: 50,
        giveCoupon: 1,
        couponDesc: '满减优惠券',
        tradeStatus: '待支付',
        createTime: '2024-01-01T16:45:00',
        description: '升级会员'
      }
    ]
    total.value = 3
    calculateTotalRevenue()
    
    if (proxy && proxy.$modal) {
      proxy.$modal.msgError('数据加载失败，显示模拟数据')
    }
  })
}

/** 计算总收益 */
function calculateTotalRevenue() {
  try {
    let revenue = 0
    if (recordList.value && Array.isArray(recordList.value)) {
      recordList.value.forEach(item => {
        if (item && item.tradeStatus === '支付成功') {
          revenue += parseFloat(item.rechargeFee || 0)
        }
      })
    }
    totalRevenue.value = revenue
    console.log('计算总收益:', revenue)
  } catch (error) {
    console.error('计算总收益失败:', error)
    totalRevenue.value = 0
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log('执行搜索')
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  console.log('执行重置')
  queryParams.value.orderNo = null
  queryParams.value.mobile = null
  queryParams.value.rechargeChannel = null
  queryParams.value.tradeStatus = null
  queryParams.value.pageNum = 1
  getList()
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getList()
}

/** 当前页改变 */
function handleCurrentChange(val) {
  queryParams.value.pageNum = val
  getList()
}

/** 格式化金额显示 */
function formatAmount(amount) {
  return parseFloat(amount || 0).toFixed(2)
}

/** 格式化时间显示 */
function formatTime(time) {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

/** 获取渠道类型 */
function getChannelType(channel) {
  const channelMap = {
    '小程序': 'primary',
    'APP': 'success',
    'H5': 'warning'
  }
  return channelMap[channel] || 'info'
}

/** 获取状态类型 */
function getStatusType(status) {
  const statusMap = {
    '待支付': 'warning',
    '支付成功': 'success',
    '支付失败': 'danger',
    '已退款': 'info'
  }
  return statusMap[status] || 'info'
}

/** 导出按钮操作 */
function handleExport() {
  console.log('执行导出')
  try {
    if (proxy && proxy.download) {
      proxy.download('order/record/export', {
        ...queryParams.value
      }, `member_recharge_record_${new Date().getTime()}.xlsx`)
    } else {
      console.warn('导出功能不可用')
      alert('导出功能暂时不可用')
    }
  } catch (error) {
    console.error('导出失败:', error)
    alert('导出失败，请重试')
  }
}

// 页面初始化
onMounted(() => {
  console.log('页面挂载完成，开始初始化...')
  console.log('当前查询参数:', queryParams.value)
  
  // 延迟执行，避免可能的竞态条件
  nextTick(() => {
    try {
      getList()
    } catch (error) {
      console.error('初始化失败:', error)
      loading.value = false
    }
  })
})
</script>
<style scoped>
.recharge-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部统计卡片 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 8px;
  padding: 20px;
  color: white;
  width: 200px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.stat-header {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-amount {
  font-size: 24px;
  font-weight: bold;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 140px;
}

.search-btn {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border: none;
  color: white;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.action-buttons .el-button {
  padding: 8px 16px;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-tips {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-stats {
  display: flex;
  gap: 20px;
  align-items: center;
}

.stat-item {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 4px;
}

.total-text {
  color: #1890ff;
  font-weight: bold;
}

/* 表格内容样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.user-icon {
  color: #1890ff;
  font-size: 16px;
}

.member-level {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.level-icon {
  color: #faad14;
  font-size: 16px;
}

.amount-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.amount-text {
  color: #52c41a;
  font-weight: 600;
  font-size: 14px;
}

.amount-text.success {
  color: #52c41a;
}

.amount-label {
  color: #999;
  font-size: 10px;
}

.gift-text {
  color: #52c41a;
  font-weight: 500;
}

.coupon-text {
  color: #722ed1;
  font-size: 12px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.time-icon {
  color: #999;
  font-size: 14px;
}

.text-muted {
  color: #999;
  font-size: 12px;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .search-select {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .stat-card {
    width: 100%;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #666;
  font-weight: 500;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-button--text) {
  padding: 0;
}

/* 顶部统计卡片 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 8px;
  padding: 20px;
  color: white;
  width: 200px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.stat-header {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-amount {
  font-size: 24px;
  font-weight: bold;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 140px;
}

.search-btn {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border: none;
  color: white;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.action-buttons .el-button {
  padding: 8px 16px;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-tips {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-stats {
  display: flex;
  gap: 20px;
  align-items: center;
}

.stat-item {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 4px;
}

.total-text {
  color: #1890ff;
  font-weight: bold;
}

/* 表格内容样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.user-icon {
  color: #1890ff;
  font-size: 16px;
}

.member-level {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.level-icon {
  color: #faad14;
  font-size: 16px;
}

.amount-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.amount-text {
  color: #52c41a;
  font-weight: 600;
  font-size: 14px;
}

.amount-text.success {
  color: #52c41a;
}

.amount-label {
  color: #999;
  font-size: 10px;
}

.gift-text {
  color: #52c41a;
  font-weight: 500;
}

.coupon-text {
  color: #722ed1;
  font-size: 12px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.time-icon {
  color: #999;
  font-size: 14px;
}

.text-muted {
  color: #999;
  font-size: 12px;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .search-select {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .stat-card {
    width: 100%;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #666;
  font-weight: 500;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-button--text) {
  padding: 0;
}
</style>